package com.thinkfit.jy.utils;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.ExifInterface;
import android.media.MediaScannerConnection;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.os.StatFs;
import android.text.TextUtils;
import android.util.Log;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * Created by you on 2016/12/2.
 */

public class FileUtils {
    /**
     * 随机命名
     */
    private static final String RANDOM_STRING = "abcdefghijklmnopqrstuvwxyz0123456789";
    /**
     * 时间命名
     */
    private static final String TIME_STRING = "yyyyMMdd_HHmmss";
    /**
     * 限制图片最大宽度进行压缩
     */
    private static final int MAX_WIDTH = 720;
    /**
     * 限制图片最大高度进行压缩
     */
    private static final int MAX_HEIGHT = 1280;
    /**
     * 上传最大图片限制
     */
    public static final int MAX_UPLOAD_PHOTO_SIZE = 300 * 1024;

    /**
     * 地震拍照 文件夹
     */
    private static final String PHOTO_FILE = "photo";

    private FileUtils() {
    }

    /**
     * 缓存文件根目录名
     */
    private static final String FILE_DIR = SystemUtils.APPNAME;
    /**
     * 上传的照片文件路径
     */
    private static final String UPLOAD_FILE = "upload";


    /**
     * 地震录屏 文件夹
     */
    private static final String VIDEO_FILE = "video";

    /**
     * 上传的照片临时文件路径
     */
    private static final String UPLOAD_TEMP = "temp";
    /**
     * 下载路径
     */
    private static final String DOWNLOAD_FILE = "download";
    /**
     * Excel路径
     */
    private static final String EXCEL_FILE = "excel";
    /**
     * 语音
     */
    private static final String SPEECH_FILE = "speech";
    /**
     * 截屏路径
     */
    private static final String SCREEN_SHOT_FILE = "screenshot";
    /**
     * 安装包文件夹
     */
    private static final String APK_FILE = "apk";

    /**
     * 图片缓存文件夹
     */
    public static final String IMAGE_CACHES_FILE = "imageCaches";

    /**
     * 日志缓存文件夹
     */
    public static final String LOG_CACHES_FILE = "logs";

    /**
     * SD卡是否存在
     */
    public static boolean isSDCardExist() {
        return Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED);
    }

    /**
     * 获取手机内部空间总大小
     *
     * @return 大小，字节为单位
     */
    public static long getTotalInternalMemorySize() {
        //获取内部存储根目录
        File path = Environment.getDataDirectory();
        //系统的空间描述类
        StatFs stat = new StatFs(path.getPath());
        //每个区块占字节数
        long blockSize = stat.getBlockSize();
        //区块总数
        long totalBlocks = stat.getBlockCount();
        return totalBlocks * blockSize;
    }

    /**
     * 获取缓存目录路径
     *
     * @return
     */
    public static String getCacheDirPath(Context context) {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }

    /**
     * 获取缓存目录
     *
     * @return
     */
    public static File getCacheDir(Context context) {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return directory;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR);
            if (!directory.exists()) directory.mkdirs();
            return directory;
        }
    }
    /**
     * @param context
     * @return 日志缓存文件夹
     */
    public static File getLogCachesFile(Context context) {
        File cacheFile = new File(FileUtils.getCacheDir(context), LOG_CACHES_FILE);
        if (!cacheFile.exists()) {
            cacheFile.mkdirs();
        }
        return cacheFile;
    }
    /**
     * @param context
     * @return 拍照文件夹
     */
    public static File getEqwPhotoFile(Context context) {
        File uploadFile = new File(getUploadFile(context), PHOTO_FILE);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        return uploadFile;
    }
    /**
     * 获取上传的路径
     *
     * @return
     */
    public static String getUploadCachePath(Context context) {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + UPLOAD_FILE + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR + File.separator + UPLOAD_FILE);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }

    /**
     * 获取上传的临时文件
     *
     * @return
     */
    public static String getUploadTempDir(Context context) {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + UPLOAD_TEMP + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR + File.separator + UPLOAD_TEMP);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }
    /**
     * 获取播报路径
     *
     * @return
     */
    public static String getSpeechPath() {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + SPEECH_FILE + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(Environment.getDownloadCacheDirectory(), FileUtils.FILE_DIR + File.separator + SPEECH_FILE);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }
    /**
     * 获取下载路径
     *
     * @param context
     * @return
     */
    public static String getDownloadPath(Context context) {
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + DOWNLOAD_FILE + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR + File.separator + DOWNLOAD_FILE);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }

    /**
     * 获取Excel路径
     * @param context
     * @return
     */
    public static String getExcelPath(Context context){
        if (isSDCardExist()) {
            String path = Environment.getExternalStorageDirectory() + File.separator + FILE_DIR + File.separator + EXCEL_FILE + File.separator;
            File directory = new File(path);
            if (!directory.exists()) directory.mkdirs();
            return path;
        } else {
            File directory = new File(context.getCacheDir(), FileUtils.FILE_DIR + File.separator + EXCEL_FILE);
            if (!directory.exists()) directory.mkdirs();
            return directory.getAbsolutePath();
        }
    }

    /**
     * jpg文件名
     *
     * @param context
     * @return
     */
    public static String getUploadPhotoFile(Context context) {
        return getUploadCachePath(context) + getTimeString() + ".jpg";
    }

    /**
     * mp4文件名
     *
     * @param context
     * @return
     */
    public static String getUploadVideoFile(Context context) {
        return getUploadCachePath(context) + getTimeString() + ".mp4";
    }

    public static String getUploadTempFile(Context context) {
        return getUploadTempDir(context) + getTimeString() + ".jpg";
    }




    /**
     * 返回SD卡路径
     */
    public static String getSDPath() {
        return isSDCardExist() ? Environment
                .getExternalStorageDirectory().getPath() : Environment
                .getDownloadCacheDirectory().getPath();
    }

    /**
     * 删除apk
     */
    public static void clearApk(final Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = getApkFile(context);
                LogUtils.d(TAG, "准备删除apk " + dir);
                List<String> files = findAllFiles(dir);
                delteFiles(dir, files);
            }
        }).start();


    }

    /**
     * @param context
     * @return
     */
    public static File getApkFile(Context context) {
        File apkFile = new File(getDownloadFile(context), APK_FILE);
        if (!apkFile.exists()) {
            apkFile.mkdirs();
        }
        return apkFile;
    }


    /**
     * @param context
     * @return 截屏文件夹
     */
    public static File getScreenShotFile(Context context) {
        File downloadFile = new File(getDownloadFile(context), SCREEN_SHOT_FILE);
        if (!downloadFile.exists()) {
            downloadFile.mkdirs();
        }
        return downloadFile;
    }

    /**
     * 获取下载路径
     *
     * @param context
     * @return
     */
    public static File getDownloadFile(Context context) {
        File downloadFile = new File(getCacheDir(context), DOWNLOAD_FILE);
        if (!downloadFile.exists()) {
            downloadFile.mkdirs();
        }
        return downloadFile;
    }

    /**
     * 获取文件夹下所有文件
     *
     * @param file
     * @return
     */
    public static List<String> findAllFiles(File file) {
        List<String> fileList = new ArrayList<>();
        if (file == null || !file.exists()) return fileList;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (!f.isDirectory()) {
                    fileList.add(f.getName());
                }
            }
        }
        return fileList;
    }

//    /**
//     * 拍照
//     *
//     * @param photoPath
//     * @param data
//     * @param rotation  手机方向
//     * @return
//     */
//    public static boolean cutAndSavePhoto(String photoPath, byte[] data, int rotation, ScanShadeView scanShadeView) {
//        Log.d(TAG, "savePhoto: "+rotation);
//        if (photoPath != null && data != null) {
//            FileOutputStream fos = null;
//            RectF f = new RectF();
//            try {
//                Bitmap preBitmap = BitmapUtils.compressBitmapAndChangeCutRectF(data, MAX_WIDTH, MAX_HEIGHT);
//
//
////                if (rotation != 0) {
////                    preBitmap = BitmapUtils.rotateBitmap(preBitmap, rotation+90, true);
////                } else {
////                System.out.println("ddddddddddddddddddddddddyyyy0:" + preBitmap.getWidth() + ":h:" + preBitmap.getHeight() );
//                preBitmap = BitmapUtils.rotateBitmap(preBitmap, rotation + 90, true);
////                System.out.println("ddddddddddddddddddddddddyyyy:" + preBitmap.getWidth() + ":h:" + preBitmap.getHeight() );
////                RectF rectF = scanShadeView.getRect(preBitmap.getWidth(), preBitmap.getHeight());
////                System.out.println("ddddddddddddddddddddddddyyyyrectF.left:" + rectF.left + ":rectF.top:" + rectF.top );
////
////
////                System.out.println("ddddddddddddddddddddddddyyyyrectF.lef1t:" + scanShadeView.getRect(preBitmap.getHeight(), preBitmap.getWidth()).left + ":rect1F.top:" + scanShadeView.getRect(preBitmap.getHeight(), preBitmap.getWidth()).top );
////                System.out.println("ddddddddddddddddddddddddyyyyrectF.lef1t:" + scanShadeView.getRect(preBitmap.getHeight(), preBitmap.getWidth()).width() + ":rect1F.top:" + scanShadeView.getRect(preBitmap.getHeight(), preBitmap.getWidth()).height()
////                    );
////                preBitmap = Bitmap.createBitmap(preBitmap, (int) rectF.left, (int) rectF.top, (int) rectF.width(), (int) rectF.height());
//                if(rotation == -90.0 || rotation == 90.0){
//                    RectF rectF = scanShadeView.getRect(preBitmap.getHeight(), preBitmap.getWidth());
//                    preBitmap = Bitmap.createBitmap(preBitmap, (int) rectF.top, (int) rectF.left, (int) rectF.height(), (int) rectF.width());
//                }else{
//                    RectF rectF = scanShadeView.getRect(preBitmap.getWidth(), preBitmap.getHeight());
//                    preBitmap = Bitmap.createBitmap(preBitmap, (int) rectF.left, (int) rectF.top, (int) rectF.width(), (int) rectF.height());
//                }
//
//
////                }
//                byte[] newDatas = BitmapUtils.compressBitmapToBytes(preBitmap, MAX_UPLOAD_PHOTO_SIZE);
//                fos = new FileOutputStream(photoPath);
//                fos.write(newDatas);
//                LogUtils.i("compress over ");
//                return true;
////                return setPictureDegreeZero(photoPath,ExifInterface.ORIENTATION_ROTATE_90);
//            } catch (Exception e) {
//                e.printStackTrace();
//                LogUtils.i(e);
//            }catch(OutOfMemoryError outOfMemoryError){
//                outOfMemoryError.printStackTrace();
//            } finally {
//                closeCloseable(fos);
//            }
//        }
//        return false;
//    }

    /**
     * @param path 图片路径
     *             修正图片的旋转角度，设置其不旋转。
     *
     */
    private static boolean setPictureDegreeZero(String path, int orientation) {
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            exifInterface.setAttribute(ExifInterface.TAG_ORIENTATION, String.valueOf(orientation));
            exifInterface.saveAttributes();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

    }

    private static final String TAG = "FileUtils";

    private static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);

            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
                default:
                    degree = 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        Log.d(TAG, "readPictureDegree: " + degree);
        return degree;
    }




    /**
     * 通知刷新相册
     *
     * @param context
     * @param path
     */
    public static void saveToGallery(Context context, String path) {
        if (TextUtils.isEmpty(path)) {
            return;
        }
        File f = new File(path);
        if (f == null || !f.isFile()) return;
        try {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                String[] paths = {path};
                String[] mimeTypes = {"image/jpeg"};
                MediaScannerConnection.scanFile(context, paths, mimeTypes,
                        new MediaScannerConnection.OnScanCompletedListener() {
                            @Override
                            public void onScanCompleted(String path, Uri uri) {
                                LogUtils.i("scanCompleted..." + path);
                            }
                        });
            } else {
                context.sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, Uri.parse("file://" + path)));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取文件路径下所有文件大小, 适当放到子线程中执行
     *
     * @param file
     * @return
     */
    public static long getFileSize(File file) {
        if (file == null || !file.exists()) return 0;
        long totalSize = 0;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                totalSize += getFileSize(f);
            }
            return totalSize;
        } else {
            return file.length();
        }
    }

    /**
     * 删除文件夹下所有文件,适当放到子线程中执行
     *
     * @param file
     */
    public static void delteFiles(File file) {
        if (file == null || !file.exists()) return;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                if (!f.isDirectory()) {
                    f.delete();
                } else {
                    delteFiles(f);
                }
            }
        } else {
            file.delete();
        }
    }
    /**
     * 删除文件夹下指定文件,适当放到子线程中执行
     *
     * @param file
     */
    public static void delteFiles(File file, List<String> nameList) {
        if (file == null || !file.exists()) return;
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            for (File f : files) {
                for (String name : nameList) {
                    if (!f.isDirectory()) {
                        if (f.getName().equals(name)) {
                            f.delete();
                            LogUtils.d(TAG, "delteFiles: " + f.getName());
                        }
                    } else {
                        delteFiles(f, nameList);
                    }
                }
            }
        } else {
            for (String name : nameList) {
                if (file.getName().equals(name)) {
                    file.delete();
                    LogUtils.d(TAG, "delteFiles: " + file.getName());

                }
            }
        }
    }

    /**
     * 关闭资源
     *
     * @param close
     */
    public static void closeCloseable(Closeable close) {
        if (close != null) {
            try {
                close.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 文件大小
     *
     * @param fileS
     * @return
     */
    public static String formetFileSize(long fileS) {
        if (fileS <= 0) return "0B";
        if (fileS < 1024) {
            return new DecimalFormat("#.00").format((double) fileS) + "B";
        } else if (fileS < 1048576) {
            return new DecimalFormat("#.00").format((double) fileS / 1024) + "KB";
        } else if (fileS < 1073741824) {
            return new DecimalFormat("#.00").format((double) fileS / 1048576) + "MB";
        } else {
            return new DecimalFormat("#.00").format((double) fileS / 1073741824) + "GB";
        }
    }

    /**
     * sd卡容量
     *
     * @return
     */
    public static long getAvailableStorage() {
        long availableSize = 0;
        if (isSDCardExist()) {
            File sdFile = Environment.getExternalStorageDirectory();
            StatFs stat = new StatFs(sdFile.getPath());
            if (Build.VERSION.SDK_INT == Build.VERSION_CODES.JELLY_BEAN_MR2) {
                availableSize = stat.getAvailableBytes();
            } else {
                availableSize = ((long) stat.getAvailableBlocks() * stat.getBlockSize());
            }
        }
        return availableSize;
    }

    /**
     * 获取随机文件名称字符串
     *
     * @param length 生成字符串的长度
     * @return
     */
    public static String getRandomString(int length) {
        Random random = new Random();
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < length; i++) {
            int number = random.nextInt(RANDOM_STRING.length());
            sb.append(RANDOM_STRING.charAt(number));
        }
        return sb.toString();
    }

    public static String getTimeString() {
        return new SimpleDateFormat(TIME_STRING).format(new Date());
    }

    /**
     * 将字符串写入文件中
     *
     * @param str    需要写入的字符串
     * @param file   写入文件的路径
     * @param append true 追加写入 false 覆盖写入
     * @return
     */
    public static boolean writeFile(String str, File file, boolean append) {
        if (TextUtils.isEmpty(str) || file == null) return false;
        FileWriter fw = null;
        try {
            fw = new FileWriter(file, append);
            fw.write(str);
            fw.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            closeCloseable(fw);
        }
        return false;
    }
    /**
     *  复制单个文件
     * @param oldPath 原文件路径
     * @param newPath 复制后路径
     */
    public static String copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) {//文件存在时
                InputStream inStream = new FileInputStream(oldPath);//读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                int value = 0 ;
                while ((byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread;//字节数 文件大小
                    value ++ ;  //计数
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
            return newPath;
        } catch (Exception e) {
            LogUtils.e("复制单个文件操作出错");
            e.printStackTrace();
            return "";
        }
    }

    /**
     * 保存日志信息
     *
     * @param context
     * @param info
     * @param fileName 保存的文件名
     * @param maxSize  保存文件最大值
     */
    public static void saveLogToFile(Context context, String info, String fileName, long maxSize) {

        StringBuilder sb = new StringBuilder();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        Date date = new Date();
        String timestamp = sdf.format(date);

        sb.append(timestamp);
        sb.append(" ");
        sb.append(info);
        sb.append("\n");

        File saveFile = new File(FileUtils.getCacheDir(context), fileName);
        boolean append = !saveFile.exists() || saveFile.length() <= maxSize;
        FileUtils.writeFile(sb.toString(), saveFile, append);
    }

    /**
     * 保存错误日志信息
     *
     * @param context
     * @param ex
     * @param fileName 保存的文件名
     * @param maxSize  保存文件最大值
     */
    public static void saveCrashInfoToFile(Context context, Throwable ex, String fileName, long maxSize) {
        Writer info = new StringWriter();
        PrintWriter printWriter = new PrintWriter(info);
        ex.printStackTrace(printWriter);

        Throwable cause = ex.getCause();
        while (cause != null) {
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }

        String result = info.toString();
        printWriter.close();

        StringBuilder sb = new StringBuilder();

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy_MM_dd HH:mm:ss");
        Date date = new Date();
        String timestamp = sdf.format(date);

        sb.append(timestamp);
        sb.append("\n");
        sb.append(result);
        sb.append("\n\n\n");

        File saveFile = new File(FileUtils.getCacheDir(context), fileName);
        boolean append = !saveFile.exists() || saveFile.length() <= maxSize;
        FileUtils.writeFile(sb.toString(), saveFile, append);

//        if (Config.isOnline) {
//            ConfigUtils.killCurrentProcess();
//        }
    }


    /**
     * @param context
     * @return 录屏文件夹
     */
    public static File getEqwVideoFile(Context context) {
        File uploadFile = new File(getUploadFile(context), VIDEO_FILE);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        return uploadFile;
    }
    /**
     * 获取上传路径
     *
     * @return
     */
    public static File getUploadFile(Context context) {
        File uploadFile = new File(getCacheDir(context), UPLOAD_FILE);
        if (!uploadFile.exists()) {
            uploadFile.mkdirs();
        }
        return uploadFile;
    }



    public static boolean saveBmpToSd(String dir, Bitmap bm, String filename, int quantity, boolean recyle) {
        boolean ret = true;
        if (bm == null) {
            return false;
        }
        File dirPath = new File(dir);
        if (!dirPath.exists()) {
            dirPath.mkdirs();
        }
        if (!dir.endsWith(File.separator)) {
            dir += File.separator;
        }
        File file = new File(dir + filename);
        OutputStream outStream = null;
        try {
            file.createNewFile();
            outStream = new FileOutputStream(file);
            bm.compress(Bitmap.CompressFormat.JPEG, quantity, outStream);
        } catch (Exception e) {
            e.printStackTrace();
            ret = false;
        } finally {
            try {
                if (outStream != null) outStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (recyle && !bm.isRecycled()) {
                bm.recycle();
                bm = null;
            }
        }
        return ret;
    }

    public static String getLastMemorySize(long size) {

        if (size > 1024) {
            size /= 1024;
            if (size > 1024) {
                size /= 1024;
                if (size > 1024) {
                    size /= 1024;
                    return size + "GB";
                } else {
                    return size + "MB";
                }
            } else {
                return size + "KB";
            }
        } else {
            return size + "B";
        }
    }
    /**
     * 获取手机内部可用空间大小
     *
     * @return 大小，字节为单位
     */
    public static long getAvailableInternalMemorySize() {
        File path = Environment.getDataDirectory();
        StatFs stat = new StatFs(path.getPath());
        long blockSize = stat.getBlockSize();
        //获取可用区块数量
        long availableBlocks = stat.getAvailableBlocks();

        return availableBlocks * blockSize;
    }


    public static void cacheFile(Context context, String fileName, String content) {
        File saveFile = new File(FileUtils.getCacheDir(context), fileName);
        FileUtils.writeFile(content, saveFile, false);
    }
    public static String getCacheFileContents(Context context, String fileName) {
        File file = new File(FileUtils.getCacheDir(context), fileName);
        if (!file.exists()) {
            try {
                file.createNewFile();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return readFile(file);
    }

    public static String readFile(File file) {
        FileInputStream in = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            in = new FileInputStream(file);
            reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                content.append(line);
                content.append("\n");
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeCloseable(reader);
        }
        return content.toString();
    }

    /**
     * 删除图片缓存
     */
    public static void clearImageCaches(final Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = getImageCachesFile(context);
                LogUtils.d(TAG, "准备删除图片缓存 " + dir);
                List<String> files = findAllFiles(dir);
                delteFiles(dir, files);
            }
        }).start();

    }
    /**
     * 删除图片
     */
    public static void clearImage(final Context context) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = getPicFile(context);
                List<String> files = findAllFiles(dir);
                delteFiles(dir, files);
            }
        }).start();

    }
    /**
     * @param context
     * @return 图片缓存文件夹
     */
    public static File getImageCachesFile(Context context) {
        File cacheFile = new File(FileUtils.getCacheDir(context), IMAGE_CACHES_FILE);
        if (!cacheFile.exists()) {
            cacheFile.mkdirs();
        }
        return cacheFile;
    }

    /**
     * 删除视频
     * @param mContext
     */
    public static void clearVideo(final Context mContext){
        new Thread(new Runnable() {
            @Override
            public void run() {
                File dir = getDownloadFile(mContext);
                File[] files = dir.listFiles();
                List<File> delFiles = new ArrayList<>();
                for(File file : files){
                    if(!file.isDirectory() && isVideoFile(file.toString())){
                        delFiles.add(file);
                    }
                }
                for(File delFile : delFiles){
                    if(delFile.exists()){
                        delFile.delete();
                    }
                }
            }
        }).start();
    }

    public static boolean isVideoFile(String filePath){
        if(StringUtils.isEmpty(filePath)){
            return false;
        }
        if(!filePath.contains(".") || filePath.split("\\.").length != 2){
            return false;
        }
        String suffix = filePath.split("\\.")[1].toLowerCase();
        return "mp4".equals(suffix) || "flv".equals(suffix) || "avi".equals(suffix) || "3gp".equals(suffix) || "mov".equals(suffix);
    }

    /**
     * @param context 清除上周之前的地震录屏
     */
//    public static void removeEqwVideoFile(final Context context) {
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //本地截屏文件夹
//                File file = getEqwVideoFile(context);
//                //本地所有截屏文件
//                List<String> files = findAllFiles(file);
//                List<String> deleteFiles = new ArrayList<>();
//                LogUtils.d(TAG, "本地地震录屏 " + new Gson().toJson(files));
//                for (String strFile : files) {
//                    if (!TextUtils.isEmpty(strFile)) {
//                        String[] arr = strFile.split("\\.");
//                        if (null != arr && arr.length == 2) {
//                            Date date = DateUtil.dateFormat(TIME_STRING, arr[0]);
//                            if (null != date) {
//                                long time = DateUtil.getDayLong(date);
//                                if (time <= -7) {
//                                    deleteFiles.add(strFile);
//                                }
//                            } else {
//                                deleteFiles.add(strFile);
//                            }
//                        } else {
//                            deleteFiles.add(strFile);
//                        }
//                    } else {
//                        deleteFiles.add(strFile);
//                    }
//                }
//                //删除过期地震录屏图文件
//                if (!deleteFiles.isEmpty()) {
//                    delteFiles(file, deleteFiles);
//                }
//            }
//        }).start();
//    }


    /**
     * 移除旧的视屏
     * 移除规则修改为：比对md5值 ，相同则不移除
     *
     * @param context
     * @param videoBeanListDownloadName
     * @param videoBeanListMd5
     */
    public static void removeOldVideos(final Context context, final List<String> videoBeanListDownloadName, List<String> videoBeanListMd5) {
//        if (null == videoBeanListDownloadName || videoBeanListMd5 == null || videoBeanListDownloadName.size() != videoBeanListMd5.size()) {
//            return;
//        }
//        new Thread(new Runnable() {
//            @Override
//            public void run() {
//                //本地文件夹
//                File file = getDownloadFile(context);
//                //本地所有文件
//                List<String> files = findAllFiles(file);
//                LogUtils.d(TAG, "本地: " + new Gson().toJson(files));
//                for (int i = 0; i < videoBeanListDownloadName.size(); i++) {
//                    for (int j = 0; j < files.size(); j++) {
//                        Log.e("本地:", files.get(j));
//                        File localVideo = new File(FileUtils.getDownloadFile(context), files.get(j));
//                        if (files.get(j).equals(videoBeanListDownloadName.get(i)) && videoBeanListMd5.equals(MD5Util.getMD5(localVideo))) {
//                            files.remove(j);
//                            j--;
//                        }
//                    }
//                }
//                //删除旧文件
//                delteFiles(file, files);
//            }
//        }).start();
    }

    /**
     * 图片下载路径
     */
    public static final String PIC_FILE = "pic";
    /**
     * 获取图片下载路径
     *
     * @param context
     * @return
     */
    public static File getPicFile(Context context) {
        File downloadFile = new File(getDownloadFile(context), PIC_FILE);
        if (!downloadFile.exists()) {
            downloadFile.mkdirs();
        }
        return downloadFile;
    }
    public static String lastUrlName(String url) {
        String endUrl = "";
        String[] spUrls = url.split("/");
        if (spUrls != null && spUrls.length > 1) {
            endUrl = spUrls[spUrls.length - 1];
        }
        return endUrl;
    }

}
